<template>
  <div>
    <div class="formula-container">
      <div class="box-header">
        <div
          class="header-text"
          :title="
            item.name.concat(
              item.type === 'dataset' ? '(数据集)' : '(Pipeline)'
            )
          "
        >
          {{ item.name }}
          <span class="type-style">
            {{ item.type === 'dataset' ? '(数据集)' : '(Pipeline)' }}
          </span>
        </div>
      </div>
      <div class="divider"></div>
      <div
        v-for="(value, index) in item.formulaList"
        :id="`formula-item-${value.id}`"
        :key="'value' + index"
        :class="{
          focus: String(value.id) === String(getHighlightFormula),
          error: ['UPDATED_FAILED', 'DELETED'].includes(value.status),
          'box-content': true,
        }"
        @click="changeSelectFormula(value.id)"
      >
        <div class="text-box">
          <div class="header-text" :title="value.formula">
            {{ value.formula }}
          </div>
          <div class="icon-list">
            <div v-for="(tip, tipIndex) in funcList" :key="'right' + tipIndex">
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{{ tip.tooltip }}</span>
                </template>
                <div
                  :class="{
                    disabled:
                      ['DELETED', 'UPDATED_FAILED'].includes(value.status) &&
                      tip.tooltip === '插入公式',
                    btn: true,
                  }"
                  @click="clickFunction(tip.click, value, item)"
                >
                  <a-icon-font :type="tip.icon" class="icon" :disabled="true" />
                </div>
              </a-tooltip>
            </div>
          </div>
        </div>

        <div v-if="['DELETED'].includes(value.status)" class="error-info">
          引用的数据节点被删除
        </div>
        <div
          v-if="['UPDATED_FAILED'].includes(value.status)"
          class="error-info"
        >
          {{ value.result }}
        </div>
      </div>
    </div>

    <div class="divider"></div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import VisualizationStore from '@/store/modules/visualization'
import { deleteFormula } from '@/api/widget'
import { cloneDeep } from 'lodash'
import { Modal } from 'ant-design-vue'

interface FormulaItem {
  formulaList: Array<FormulaDetail>
  name: string
  taskId: number
  type: string
}

interface FormulaDetail {
  formula: string
  id: number
  result: string
  status?: string
  name?: string
  taskId?: number
  type?: string
}

// enum FormulaStatusEnum {
//   pieChart = 'pieChart',
//   original = 'ORIGINAL',
//   updated_success = 'UPDATED_SUCCESS',
//   updated_failed = 'UPDATED_FAILED',
//   deleted = 'DELETED'
// }

@Component({
  components: {
    // Editor,
  },
})
export default class FormulaList extends Vue {
  @Prop({
    default() {
      return {}
    },
  })
  public item!: FormulaItem

  public get getHighlightFormula() {
    return VisualizationStore.getHighlightFormula
  }

  public detectFormulaInText: any = []

  @Watch('getHighlightFormula')
  private handleHighlightFormula(newValue: number) {
    ;(document.querySelector(
      `#formula-item-${newValue}`
    ) as HTMLElement).scrollIntoView()
  }

  public changeSelectFormula(id: number) {
    VisualizationStore.setHighlightFormula(id)
  }

  public funcList: any[] = [
    {
      tooltip: '编辑公式',
      click: 'editFormula',
      icon: 'icontaosuoshubiao',
    },
    {
      tooltip: '插入公式',
      click: 'insertFormula',
      icon: 'iconcharugongshi',
    },
    {
      tooltip: '删除公式',
      click: 'deleteFormula',
      icon: 'iconicon-beifen5',
    },
  ]

  // 多个功能 统一点击入口
  public clickFunction(functionName: string, value: FormulaDetail, item?: any) {
    switch (functionName) {
      case 'editFormula':
        this.editFormula(value, item)
        break
      case 'insertFormula':
        this.insertFormula(value)
        break
      case 'deleteFormula':
        this.deleteProcess(value)
        break
      default:
        break
    }
  }
  //  是否删除的公式被文本组件引用
  private checkIfExistFormula(targetId: number) {
    this.detectFormulaInText = []
    const elements = document.querySelectorAll('.mceNonEditable')
    if (elements.length > 0) {
      // eslint-disable-next-line no-restricted-syntax
      for (const item of elements) {
        const id = item.getAttribute('data-id')
        if (targetId === Number(id)) {
          this.detectFormulaInText.push(item)
        }
      }
      if (this.detectFormulaInText.length > 0) {
        return true
      }
    }
    return false
  }

  public async deleteProcess(item: FormulaDetail) {
    const that = this
    //  TBD check it the formula exit in the text Comp
    if (this.checkIfExistFormula(item.id)) {
      Modal.confirm({
        title: `"${item.formula}"已在文本中使用，确定删除吗？`,
        content: '删除将会同时从文本中删除。',
        okText: '确定',
        cancelText: '取消',
        centered: true,
        async onOk() {
          that.deleteFormula(item)
          that.invalidateFormula(item)
        },
      })
    } else {
      this.deleteFormula(item)
    }
  }

  public invalidateFormula(item: FormulaDetail) {
    VisualizationStore.setDeleteFormula(item)
  }

  public async deleteFormula(item: FormulaDetail) {
    const that = this
    const response: any = await deleteFormula({
      data: {
        formulaId: item.id,
      },
    })
    if (
      response.data.code === 100 &&
      response.data.result.status === 'SUCCESS'
    ) {
      that.$message.success('删除公式成功')
      //  query formula list again; 如果有公式已经被用到了文本组件中，该如何处理？？
      VisualizationStore.fetchFormulaList({
        projectId: Number(that.$route.params.id),
      })
    } else {
      that.$message.error('删除公式失败')
    }
  }

  public editFormula(value: FormulaDetail, item: FormulaItem) {
    const name = value.status === 'DELETED' ? '' : item.name
    const { taskId, type } = item
    const result: any = {
      ...cloneDeep(value),
      name,
      taskId,
      type,
    }
    //  type
    VisualizationStore.updateEditFormula(result)
  }

  public insertFormula(item: any) {
    //  fix 连续插入同一个公式 issue
    VisualizationStore.updateInsertFormula({})
    VisualizationStore.updateInsertFormula(item)
  }
}
</script>

<style lang="less" scoped>
.formula-container {
  background-color: #fff;
  border: 1px solid #e9e9e9;
  border-radius: 2px;

  .box-header {
    background-color: #eff0fe;
    padding: 6px 8px;
  }

  .header-text {
    height: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    .type-style {
      color: #5d637e;
      font-size: 14px;
    }
  }

  .divider {
    border-top: 1px solid #e9e9e9;
    height: 1px;
    margin: 0;
    width: 100%;
  }

  .box-content {
    border: 1px solid #fff;
    border-bottom: 1px solid #e9e9e9;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 8px;

    .text-box {
      display: flex;
      justify-content: space-between;
    }

    .icon-list {
      display: flex;

      .icon {
        height: 12px;
        width: 12px;
      }

      .btn {
        align-items: center;
        border-radius: 2px;
        color: rgb(93, 99, 126);
        cursor: pointer;
        display: flex;
        height: 22px;
        justify-content: center;
        position: relative;
        width: 22px;

        &:hover {
          background-color: rgba(105, 115, 255, 0.1);
          color: #6973ff;
        }
      }

      .btn.disabled {
        opacity: 0.5;
        pointer-events: none;
      }
    }

    &:last-child {
      border-bottom: 1px solid #fff;
    }
  }
}

.box-content.focus {
  border: 1px solid #6973ff !important;
}

.box-content.error {
  border: 1px solid #e6505a !important;
}

.error-info {
  color: #e6505a;
}

.divider {
  border-top: 1px solid #e9e9e9;
  height: 1px;
  margin: 16px 0;
  width: 100%;
}
</style>
